#include<iostream>
#include<cstdio>
#include<cstring>
#include<unistd.h>
#include<cassert>
#include<cstdlib>
#include<sys/wait.h>
using namespace std;
//The parent process reads and the child process writes
int main(){
    int pipefd[2] = { 0 };
    int n = pipe(pipefd);
    assert(!n);
    //stdin:0  stdout:1  stderr:2 
    cout <<"pipefd[0]:"<< pipefd[0] << endl;  //pipefd[0] == read
    cout <<"pipefd[1]:"<< pipefd[1] << endl;  //pipefd[1] == write 
    pid_t id = fork();
    assert(id>=0);
    if(!id){
        close(pipefd[0]);
        size_t cnt = 0;
        while(true){
            cnt++;
            char buffer_c[1024] = { 0 };
            sprintf(buffer_c,"child -> parent child id: %d cnt:%d",getpid(),cnt);
            write(pipefd[1],buffer_c,strlen(buffer_c));
            sleep(1);
            //break;
        }
        close(pipefd[1]);
        exit(-1);
    }
    close(pipefd[1]);
    while(true){
        char buffer_p[1024] = { 0 }; 
        //cout << "AAAAAAAAAAAAAAAAAA" << endl;
        size_t sz = read(pipefd[0],buffer_p,sizeof(buffer_p)-1);
        //cout << "BBBBBBBBBBBBBBBBBB" << endl;
        if(sz > 0){
            buffer_p[sz] = '\0';
            cout << "parent id "<< getpid() <<" receive message :" << buffer_p << endl;
        } 
        // The read function is blocking and waiting by default. 
       //The read function will wait until there is data to read 
       //or an error occurs before returning. If the requested data
       // is not ready yet, it will cause the calling process to 
       //hang until there is readable data or an error occurs
       sleep(1);
    }
    n = waitpid(id,nullptr,0);
    assert(n > 0);
    close(pipefd[0]);
    return 0;
}